package cn.jhc.db;

import java.sql.SQLException;
import java.util.List;

import javax.sql.DataSource;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import cn.jhc.bean.Admin;
import cn.jhc.bean.User;



public class AdminDao {

	private  DataSource dataSource = null;
	
	public AdminDao(DataSource dataSource){
		this.dataSource = dataSource;
	}
	
	public void DropAdmin(Admin admin) throws SQLException{
		QueryRunner runner = new QueryRunner(dataSource);
		String sql = "drop table admin";
		runner.update(sql);
		}
	public void addAdmin(Admin admin) throws SQLException{
		QueryRunner runner = new QueryRunner(dataSource);
		String sql = "insert into admin(username,password)values(?,?)";
		runner.insert(sql, new BeanHandler<>(Admin.class),admin.getUsername(),admin.getPassword());
	}
	
	public void delectAll() throws SQLException{
		QueryRunner runner = new QueryRunner(dataSource);
		runner.update("delete from admin");
	}
	
	public List<Admin> findAll(){
		List<Admin> list = null;
		QueryRunner runner = new QueryRunner(dataSource);
		String sql ="select  * from admin";
		ResultSetHandler<List<Admin>> h = new BeanListHandler<>(Admin.class);
		try {
			list = runner.query(sql, h);
		} catch (SQLException e) {
			// TODO Auto-generated catch block


			e.printStackTrace();
		}
		return list;
	}

	public boolean selectbyname(Admin admin) {
		boolean a=false;
		QueryRunner runner = new QueryRunner(dataSource);
		String selectsql = "select username from admin where username='"+admin.getUsername()+"'";
		try {
			String name = (String)runner.query(selectsql, new ScalarHandler<>());
			if (name ==null) {
				a= true;
			}
			else {
				a= false;
			}
		} catch (SQLException e) {
			
			e.printStackTrace();
		}
		return a;
		
	
		
	}
}
